<template>
  <div class="c-digit">
    <!-- <div class="c-digit-item">￥</div> -->
    <slot name="header"></slot>
    <div
      ref="item"
      class="c-digit-item"
      :class="num.className"
      :style="css"
      v-for="(num,index) in nums"
      :key="`digit-item-${index}`"
    >
      {{num.val}}
      <canvas :width="width" :height="height" class="digit-item_bg"></canvas>
    </div>
    <slot name="footer"></slot>
  </div>
</template>

<script>
export default {
  name: "data-v-digit",
  props: {
    /* 要显示的数字 */
    num: {
      type: [Number, String],
      default: 0
    },
    width: {
      type: [Number, String],
      default: 23
    },
    height: {
      type: [Number, String],
      default: 30
    },
    color: {
      type: String,
      default: "#0ff"
    },
    /* 长度是否固定 */
    fixed: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    format(val) {
      if (this.fixed) {
        val = String(val).padStart(9, "0");
      }
      return String(val).replace(/(\d)(?=(\d{3})+$)/g, "$1,");
    },
    drawBg(ctx) {
      // 折角长度
      let angleLength = 10;
      // 线宽
      let lineWidth = 3;

      ctx.save();
      ctx.strokeStyle = this.color;
      ctx.lineWidth = lineWidth;
      ctx.rect(0, 0, this.width, this.height);
      ctx.stroke();
      ctx.clearRect(angleLength, 0, this.width - angleLength * 2, this.height);
      ctx.clearRect(0, angleLength, this.width, this.height - angleLength * 2);
      ctx.restore();
    }
  },
  computed: {
    nums() {
      let str = this.format(this.num);
      return Array.from(str).map(s => ({
        val: s,
        className: s === "," ? "split" : null
      }));
    },
    css() {
      return {
        width: this.width + "px",
        height: this.height + "px",
        color: this.color
        // borderColor: this.color
      };
    }
  },
  mounted() {
    let items = this.$refs["item"];
    items.forEach(item => {
      let canvas = item.children[0];
      let context = canvas.getContext("2d");
      this.drawBg(context);
    });
  }
};
</script>

<style>
.c-digit {
  display: flex;
  /* justify-content: center; */
  align-items: center;
}
.c-digit-item {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  /* width: 23px;
  height: 30px; */
  font-size: 22px;
  color: #0ff;
  border: 1px solid #4e6b8d;
}
.c-digit-item > .digit-item_bg {
  position: absolute;
}
.c-digit-item + .c-digit-item {
  margin-left: 4px;
}
/* .c-digit-item::before,
.c-digit-item::after {
  content: "";
  position: absolute;
  left: -1px;
  width: 23px;
  height: 4px;
  background: url(img/focus.png) center top no-repeat;
}
.c-digit-item::before {
  top: -1px;
}
.c-digit-item::after {
  bottom: -1px;
  transform: rotate(180deg);
} */
.c-digit-item.split {
  width: 18px;
  border: none;
}
.c-digit-item.split::before,
.c-digit-item.split::after {
  background: transparent;
}
</style>